package com.lw.common.network.request

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.hjq.toast.Toaster
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

fun <T> launchFlow(
    requestBlock: suspend () -> ApiResponse<T>,
    startCallback: (() -> Unit)? = null,
    completeCallback: (() -> Unit)? = null,
): Flow<ApiResponse<T>> {
    return flow {
        emit(requestBlock())
    }.onStart {
        startCallback?.invoke()
    }.onCompletion {
        completeCallback?.invoke()
    }
}


/**
 * 请求不带Loading&&不需要声明LiveData
 */
fun <T> IUiView.requestApi(
    requestBlock: suspend () -> ApiResponse<T>,
    toast: Boolean = false,
    listenerBuilder: ResultBuilder<T>.() -> Unit,
) {
    lifecycleScope.launch {
        launchFlow(requestBlock).collect { response ->
            if (toast) {
                Toaster.show(response.msg)
            }
            response.parseData(listenerBuilder)
        }
    }
}

/**
 * 请求带Loading&&不需要声明LiveData
 */
fun <T> IUiView.requestWithLoading(
    requestBlock: suspend () -> ApiResponse<T>,
    loadingText: String = "正在加载...",
    toast: Boolean = false,
    listenerBuilder: ResultBuilder<T>.() -> Unit,
) {
    lifecycleScope.launch {
        launchFlow(requestBlock, { showLoading(loadingText) }, { dismissLoading() }).collect { response ->
            if (toast) {
                Toaster.show(response.msg)
            }
            response.parseData(listenerBuilder)
        }
    }
}



